/**
 * 
 */
package com.zznode.client.wlanpolling.service.net;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import android.content.Context;
import android.net.wifi.WifiManager;

import com.zznode.client.wlanpolling.utils.WLanPollingUtils;
import com.zznode.client.wlanpolling.utils.WifiUtils;

/**
 * @author Bean
 *
 */
public abstract class HttpExecutor {
	private static Logger logger = Logger.getLogger(HttpExecutor.class);
	
	protected List<HttpParam> params = new ArrayList<HttpParam>();
	protected String url;
	protected Context context;
	
	protected long startTime;
	
	public HttpExecutor(Context context) {
		this.context = context;
	}
	
	/**
	 * 增加请求参数
	 * @param param
	 */
	public void addParam(HttpParam param) {
		if(param == null) 
			return;
		
		if(!params.contains(param)) {
			params.add(param);
		}
	}
	
	public void removeParam(HttpParam param) {
		if(param == null)
			return;
		
		if(params.contains(param)) {
			params.remove(param);
		}
	}
	
	public String getUrl() {
		return url;
	}
	

	public void setUrl(String url) {
		this.url = url;
	}
	
	public  byte[] syncExecute() throws HttpException {
		startTime = System.currentTimeMillis();
		byte[] data = onSyncExecute();
		long end = System.currentTimeMillis();
		
		if(logger.isDebugEnabled()) {
			logger.debug(formatNetLog(end - startTime, data));
		}
		return data;
	}
	
	public void asyncExecute(HttpCallback callback, int tag) {
		onAsyncExecute(callback, tag);
	}
	
	protected abstract byte[] onSyncExecute() throws HttpException;
	protected abstract void onAsyncExecute(HttpCallback callback, int tag);
	
	protected void checkNetWorkAvailable() throws HttpException {
		WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
		if(!WifiUtils.canUseWifi(wifiManager.getConnectionInfo(), context)) {
			throw new HttpException("当前AP无法连接到网络,请确保AP可用或稍后重试!");
		}
	}
	
	private String formatNetLog(long costTime, byte[] response) {
		StringBuffer sb = new StringBuffer();
		sb.append("URL : ").append(url).append("\r\n");
		sb.append("Request Params : ");
		for(HttpParam param : params) {
			sb.append(param.getName()).append("=").append(param.getValue()).append("&");
		}
		sb.append("\r\n");
		sb.append("CostTime : ").append(costTime).append("ms").append("\r\n");
		if(response != null && response.length > 0) {
			try {
				sb.append("Response Data :").append(new String(response, WLanPollingUtils.DEFAULT_CHARSET));
			} catch(Throwable e) {
				sb.append("Response parse error!");
			}
		}
		sb.append("\r\n");
		
		return sb.toString();
	}
}
